using Microsoft.AspNetCore.Mvc;
using JTZY.Model.Goods.Dto;
using JTZY.Model.Goods;
using JTZY.Service.Goods.IGoodsService;
using JTZY.Admin.WebApi.Filters;
using JTZY.Model.Order.Dto;
using Infrastructure;
using JTZY.Service.Goods;
using Aliyun.OSS;
using System.Threading.Tasks;
using JTZY.Model.Content.Dto;
using JTZY.Model.System;
using MiniExcelLibs;
using Essensoft.Paylink.WeChatPay.V3.Domain;

//创建时间：2024-11-25
namespace JTZY.Admin.WebApi.Controllers.Goods
{
    /// <summary>
    /// 良品仓
    /// </summary>
    [Verify]
    [Route("goods/Corecmsuserstock")]
    public class CorecmsuserstockController : BaseController
    {
        /// <summary>
        /// 良品仓接口
        /// </summary>
        private readonly ICorecmsuserstockService _CorecmsuserstockService;

        public CorecmsuserstockController(ICorecmsuserstockService CorecmsuserstockService)
        {
            _CorecmsuserstockService = CorecmsuserstockService;
        }

        /// <summary>
        /// 查询良品仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:list")]
        public IActionResult QueryCorecmsuserstock([FromQuery] CorecmsuserstockQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();

            var response = _CorecmsuserstockService.GetList(parm);
            return SUCCESS(response);
        }

        [HttpGet("ministocklist")]
        [ActionPermissionFilter(Permission = "corecmsusergoods:list")]
        public IActionResult QueryMinistockList([FromQuery] CorecmsuserstockQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();

            var response = _CorecmsuserstockService.GetKtList(parm);
            return SUCCESS(response);
        }

        [HttpGet("warehouselist")]
        [ActionPermissionFilter(Permission = "corecmsusergoods:list")]
        public IActionResult QueryWarehouseList()
        {
            var UserId = HttpContext.GetUId();

            var response = _CorecmsuserstockService.QueryWarehouseList(UserId);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询良品仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("clist")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:list")]
        public IActionResult QueryCorecmscusstock([FromQuery] CorecmsuserstockQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();

            var response = _CorecmsuserstockService.GetCustomerList(parm);
            return SUCCESS(response);
        }

        [HttpPost("marketable")]
        [ActionPermissionFilter(Permission = "corecmsagentproducts:edit")]
        [Log(Title = "代理货品池", BusinessType = BusinessType.UPDATE)]
        public IActionResult Marketable([FromBody] CorecmsuserstockDto parm)
        {
            var modal = parm.Adapt<Corecmsuserstock>().ToUpdate(HttpContext);
            modal.Marketable = modal.Marketable == 1 ? 0 : 1;
            //上架需要刷新库存价格 暂未实现
            var response = _CorecmsuserstockService.Marketable(modal);

            return ToResponse(response);
        }

        [HttpGet("getlist/{goodId}")]
        public IActionResult GetList([FromRoute] int goodId)
        {
            long UserId = HttpContext.GetUId();

            var response = _CorecmsuserstockService.GetUserStockList(UserId, goodId);

            return SUCCESS(response);
        }

        /// <summary>
        /// 查询良品仓详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:query")]
        public IActionResult GetCorecmsuserstock(long Id)
        {
            var response = _CorecmsuserstockService.GetInfo(Id);

            var info = response.Adapt<CorecmsuserstockDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 添加良品仓
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "corecmsuserstock:add")]
        [Log(Title = "良品仓", BusinessType = BusinessType.INSERT)]
        public IActionResult AddCorecmsuserstock([FromBody] CorecmsuserstockDto parm)
        {
            var modal = parm.Adapt<Corecmsuserstock>().ToCreate(HttpContext);

            var response = _CorecmsuserstockService.AddCorecmsuserstock(modal);

            return SUCCESS(response);
        }

        /// <summary>
        /// 更新良品仓
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "corecmsuserstock:edit")]
        [Log(Title = "良品仓", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateCorecmsuserstock([FromBody] CorecmsuserstockDto parm)
        {
            var modal = parm.Adapt<Corecmsuserstock>().ToUpdate(HttpContext);
            var response = _CorecmsuserstockService.UpdateCorecmsuserstock(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除良品仓
        /// </summary>
        /// <returns></returns>
        [HttpPost("delete/{ids}")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:delete")]
        [Log(Title = "良品仓", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteCorecmsuserstock([FromRoute] string ids)
        {
            var idArr = Tools.SplitAndConvert<long>(ids);

            return ToResponse(_CorecmsuserstockService.Delete(idArr));
        }


        [HttpPost("updatevipprice")]
        [Log(Title = "良品仓", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateVipPrice([FromBody] UpdateVipPriceDto parm)
        {
            parm.UserId = HttpContext.GetUId();
            bool res = _CorecmsuserstockService.UpdateVipPrice(parm);
            return ToResponse(res ? ResultCode.SUCCESS : ResultCode.FAIL);
        }

        /// <summary>
        /// 查询良品仓统计
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("getuserstock")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:query")]
        public IActionResult GetUserStock([FromQuery] CorecmsuserstockQueryDto parm)
        {

            parm.UserId = HttpContext.GetUId();
            var response = _CorecmsuserstockService.GetUserStock(parm);

            var info = response.Adapt<CorecmsuserstockDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 修改库存警戒线
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("updatestockwarn")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:updatestockwarn")]
        public IActionResult UpdateStockWarn([FromBody] StockWarnUpdataDto parm)
        {

            var response = _CorecmsuserstockService.UpdateStockWarnLine(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询良品仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("purlist")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:purlist")]
        public IActionResult QueryCorecmsuserstock([FromQuery] PurStockManageQueryDto parm)
        {
            var response = _CorecmsuserstockService.GetPurStockManageList(parm);
            return SUCCESS(response);
        }
        /// <summary>
        /// 设置销售价获取
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("purdetail")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:purdetail")]
        public async Task<IActionResult> QueryDetailCorecmsuserstock([FromQuery] PurStockManageDetailQueryDto parm)
        {
            var response = await _CorecmsuserstockService.GetPurStockDetailByGoodsId(parm);
            return SUCCESS(response);
        }
        /// <summary>
        /// 设置销售价获取
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("getstockwarnline")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:getstockwarnline")]
        public async Task<IActionResult> QueryStockWarnLine([FromQuery] PurStockManageDetailQueryDto parm)
        {
            var response = await _CorecmsuserstockService.GetPurStockWarnLineByGoodsId(parm);
            return SUCCESS(response);
        }
        /// <summary>
        /// 更新增值价
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("updateinvalvip")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:updateinvalvip")]
        public IActionResult UpdateInvalVipPrice([FromBody] InvalVipPriceUpdateDto parm)
        {

            var response = _CorecmsuserstockService.UpdatePurStockInvalVipPrice(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 更新销售价
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("updatevipsaleprice")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:updatevipsaleprice")]
        public IActionResult UpdateVipSalePrice([FromBody] PurStockManageMasterhDto parm)
        {

            var response = _CorecmsuserstockService.UpdateVipSalePrice(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 更新销售价
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("updatestockwarnline")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:updatestockwarnline")]
        public IActionResult UpdateStockWarnLine([FromBody] PurStockManageMasterhDto parm)
        {
            var response = _CorecmsuserstockService.UpdateStockWarnLine(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 导出铺货信息
        /// </summary>
        /// <returns></returns>

        [HttpGet("exportpurlist")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:export")]
        public IActionResult Export([FromQuery] PurStockManageQueryDto parm)
        {
            parm.PageSize = 10000;
            var list = _CorecmsuserstockService.GetExportPurStockManageList(parm).Result;

            string sFileName = ExportExcel(list, "corecmsuserstock", "铺货信息");
            return SUCCESS(new { path = "/export/" + sFileName, fileName = sFileName });
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="formFile">使用IFromFile必须使用name属性否则获取不到文件</param>
        /// <returns></returns>
        [HttpPost()]
        [Verify]
        [ActionPermissionFilter(Permission = "corecmsuserstock:importDistribution")]
        public IActionResult importDistribution(IFormFile formFile)
        {
            string userId = string.Empty;
            if (HttpContext.Request.Headers.TryGetValue("userId", out var headerValues))
            {
                userId = headerValues.FirstOrDefault();
            }
            List<ImportPurStockDto> list = new();
            using (var stream = formFile.OpenReadStream())
            {
                list = stream.Query<ImportPurStockDto>(startCell: "A1").ToList();
            }

            _CorecmsuserstockService.ImportDistribution(long.Parse(userId), list);
            return SUCCESS("");
        }

        [HttpPost()]
        [Verify]
        [ActionPermissionFilter(Permission = "corecmsuserstock:importDistributionAppend")]
        public IActionResult importDistributionAppend(IFormFile formFile)
        {
            string userId = string.Empty;
            if (HttpContext.Request.Headers.TryGetValue("userId", out var headerValues))
            {
                userId = headerValues.FirstOrDefault();
            }
            List<ImportPurStockDto> list = new();
            using (var stream = formFile.OpenReadStream())
            {
                list = stream.Query<ImportPurStockDto>(startCell: "A1").ToList();
            }

            _CorecmsuserstockService.ImportDistribution(long.Parse(userId), list, true);
            return SUCCESS("");
        }

        /// <summary>
        /// 补货
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("restocklist")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:restocklist")]
        public async Task<IActionResult> GetReStockList([FromQuery] ReStockQueryDto parm)
        {
            var list = await _CorecmsuserstockService.GetReStockList(parm,HttpContext.GetUId());
            return SUCCESS(list);
        }


        [HttpPost("restockadd")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:restockadd")]
        public IActionResult ReStockAdd([FromBody] List<PurStockManageMasterhDto> parm)
        {
            
            var list = _CorecmsuserstockService.ReStockAdd(parm, HttpContext.GetUId());
            return SUCCESS(list);
        }

        /// <summary>
        /// 导出商品表
        /// </summary>
        /// <returns></returns>
        [Log(Title = "良品仓", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:export")]
        public IActionResult Export([FromQuery] CorecmsuserstockQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();
            parm.PageNum = 1;
            parm.PageSize = 100000;
            var list = _CorecmsuserstockService.ExportList(parm).Result;
            if (list == null || list.Count <= 0)
            {
                return ToResponse(ResultCode.FAIL, "没有要导出的数据");
            }
            var result = ExportExcelMini(list, "本店良品仓表", "本店良品仓表");
            return ExportExcel(result.Item2, result.Item1);
        }

        /// <summary>
        /// 导出商品表
        /// </summary>
        /// <returns></returns>
        [Log(Title = "小仓", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpGet("exportmini")]
        [ActionPermissionFilter(Permission = "corecmsuserstock:export")]
        public IActionResult ExportMini([FromQuery] CorecmsuserstockQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();
            parm.PageNum = 1;
            parm.PageSize = 100000;
            var list = _CorecmsuserstockService.ExportMiniList(parm).Result;
            if (list == null || list.Count <= 0)
            {
                return ToResponse(ResultCode.FAIL, "没有要导出的数据");
            }
            var result = ExportExcelMini(list, "小仓良品", "小仓良品");
            return ExportExcel(result.Item2, result.Item1);
        }

    }
}